const audioPlayer = document.getElementById('audioPlayer');
const playPauseBtn = document.getElementById('playPauseBtn');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const playlistContainer = document.getElementById('playlist');
const seekBar = document.getElementById('seekBar');
const musicPlayer = document.querySelector('.music-player');
const musicDisk = document.querySelector('.music-disk');
// 获取 body 元素
const body = document.body; 

let currentTrackIndex = 0;
const playlist = [
    { title: '富士山下', src: 'music1.mp3', img: 'image1.jpg', bg: 'picture1.jpg' },
    { title: '十年', src: 'music2.mp3', img: 'image2.jpg', bg: 'picture2.jpg' },
    { title: '稳稳的幸福', src: 'music3.mp3', img: 'image3.jpg', bg: 'picture3.png' }
];

// 加载播放列表
function loadPlaylist() {
    playlistContainer.innerHTML = '';
    playlist.forEach((track, index) => {
        const li = document.createElement('li');
        li.textContent = track.title;
        li.addEventListener('click', () => {
            currentTrackIndex = index;
            loadTrack();
            audioPlayer.play();
        });
        playlistContainer.appendChild(li);
    });
}

// 加载当前歌曲
function loadTrack() {
    const currentTrack = playlist[currentTrackIndex];
    audioPlayer.src = currentTrack.src;
    audioPlayer.load();
    musicDisk.style.backgroundImage = `url(${currentTrack.img})`;
    musicDisk.style.backgroundSize = 'cover';
    // 更新页面背景图片
    body.style.backgroundImage = `url(${currentTrack.bg})`; 
}

// 播放/暂停
playPauseBtn.addEventListener('click', () => {
    if (audioPlayer.paused) {
        audioPlayer.play();
        playPauseBtn.textContent = '暂停';
        musicPlayer.classList.add('playing');
    } else {
        audioPlayer.pause();
        playPauseBtn.textContent = '播放';
        musicPlayer.classList.remove('playing');
    }
});

// 上一曲
prevBtn.addEventListener('click', () => {
    currentTrackIndex = (currentTrackIndex - 1 + playlist.length) % playlist.length;
    loadTrack();
    audioPlayer.play();
    musicPlayer.classList.add('playing');
});

// 下一曲
nextBtn.addEventListener('click', () => {
    currentTrackIndex = (currentTrackIndex + 1) % playlist.length;
    loadTrack();
    audioPlayer.play();
    musicPlayer.classList.add('playing');
});

// 进度条更新
audioPlayer.addEventListener('timeupdate', () => {
    const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;
    seekBar.value = progress;
});

// 进度条拖动
seekBar.addEventListener('input', () => {
    const time = (seekBar.value / 100) * audioPlayer.duration;
    audioPlayer.currentTime = time;
});

// 初始化
loadPlaylist();
loadTrack();